<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2019/1/23
 * Time: 上午10:34
 */

namespace App\Http\Model;


use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Queue extends Base
{
    protected $table = "queue";
    protected $primaryKey = 'id';



    const QUEUE_STATE_RUN = 0;
    const QUEUE_STATE_END = 1;

    const QUEUE_UNLOCK = 0;
    const QUEUE_LOCK = 1;

    const QUEUE_LIMIT = 1;



    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }


    public function add($data)
    {
        $data['add_time'] = time();
        return DB::table($this->table)->insert($data);
    }

    public function getQueuePop($queueName)
    {
        $queue = DB::table($this->table)
            ->where('name', '=', $queueName)
            ->where('state', '=', self::QUEUE_STATE_RUN)
            ->where('is_lock', '=', self::QUEUE_UNLOCK)
            ->where('run_time', '<=', time())
            ->orderBy('id')
            ->first(['id','name','params']);

        return self::objToArray($queue);
    }



    public function queueLock($queueId)
    {
        $queue = DB::table($this->table)
            ->where('id', '=', $queueId)
            ->update(['is_lock'=>self::QUEUE_LOCK, 'lock_time'=>time()]);
        return $queue;
    }

    public function queueEnd($queueId)
    {
        $queue = DB::table($this->table)
            ->where('id', '=', $queueId)
            ->update(['state'=>self::QUEUE_STATE_END, 'end_time'=>time()]);
        return $queue;
    }


}
